//
//  OrderChildController.m
//  StarOrangeStaff
//
//  Created by lshenrong on 2020/7/19.
//  Copyright © 2020 lshenrong. All rights reserved.
//

#import "OrderChildController.h"
#import "MyOderListAPI.h"
#import "OrderListCell.h"

@interface OrderChildController () <UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UISearchBar *searchBar;
@property (nonatomic,strong) NSMutableArray *searchArray;
@property (nonatomic,assign) BOOL isSearchMode;//是否是搜索模式下
@property (nonatomic, assign) NSInteger searchInputCount; //用户输入次数记录,用来控制延迟搜索请求
@property (nonatomic,assign) NSInteger currentSearchPageNumber;//搜索页面编号，从1开始
@property (nonatomic,copy) NSString *searchKey;


@end

@implementation OrderChildController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentSearchPageNumber = 1;
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = kSeparateLineColor;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.left.right.bottom.mas_equalTo(self.view);
    }];
    [UIConfigure configRefreshInTableView:self.tableView target:self action:@selector(resetRefreshData)];

}

#pragma mark - action

- (void)refreshProduct{
    self.tableDataExtend.pageNum = 1;
//    MyOderListAPI *api = [[MyOderListAPI alloc] initWithPageSize:self.tableDataExtend.pageSize index:self.tableDataExtend.pageNum sortType:self.sortType sortRule:self.sortRule status:self.getStatus];
//    [api startCedarRequestWithCompletionBlock:^(CedarBaseResponse * _Nullable response) {
//        if (response.code!= ResponseTypeScuess) {
//            [self.tableView.mj_header endRefreshing];
//            return;
//        }
//        ProductListRsp *rsp = [ProductListRsp mj_objectWithKeyValues:response.dataObject];
//        BOOL isNoMoreData = NO;
//
//        if ([rsp.recordList count]>0) {
//            [self addRefreshFooter];
//            [self.tableView.mj_footer resetNoMoreData];
//            [self.tableDataExtend resetAddNewArrayData:rsp.recordList];
//            if(self.tableDataExtend.listData.count>=rsp.totalCount){//没数据了
//                isNoMoreData = YES;
//            }
//            [self hidenNoContentImageView];
//        }else{
//             [self showNoContentImageView:response.msg];
//            [self.tableDataExtend removeAllListData];
//        }
//        [self.tableView reloadData];
//        [self.tableView.mj_header endRefreshing];
//        if(isNoMoreData){
//            [self.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
//    }];
}


- (void)loadMoreProduct{
    self.tableDataExtend.pageNum++;
//    ProductListAPI *api = [[ProductListAPI alloc]initWithPageSize:self.tableDataExtend.pageSize index:self.tableDataExtend.pageNum sortType:self.sortType sortRule:self.sortRule status:self.getStatus];
//    [api startCedarRequestWithCompletionBlock:^(CedarBaseResponse * _Nullable response) {
//        if (response.code!= ResponseTypeScuess) {
//            [self.tableView.mj_footer endRefreshing];
//            return;
//        }
//        ProductListRsp *rsp = [ProductListRsp mj_objectWithKeyValues:response.dataObject];
//        BOOL isNoMoreData = NO;
//        if ([rsp.recordList count]>0) {
//            [self.tableDataExtend addNewArrayData:rsp.recordList];
//            [self.tableView reloadData];
//            [self.tableView.mj_footer endRefreshing];
//            if(self.tableDataExtend.listData.count>=rsp.totalCount){//没数据了
//                isNoMoreData = YES;
//            }
//        }
//        if(isNoMoreData){
//            [self.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
//    }];
}

//搜索
- (void)refreshProductWithSearch {
    self.currentSearchPageNumber = 1;
//    ProductListAPI *api = [[ProductListAPI alloc]initWithPageSize:self.tableDataExtend.pageSize index:self.currentSearchPageNumber sortType:self.sortType sortRule:self.sortRule status:self.getStatus];
//    api.keyword = self.searchKey;
//    [api startCedarRequestWithCompletionBlock:^(CedarBaseResponse * _Nullable response) {
//        if (response.code!= ResponseTypeScuess) {
//            [self.tableView.mj_header endRefreshing];
//            return;
//        }
//        ProductListRsp *rsp = [ProductListRsp mj_objectWithKeyValues:response.dataObject];
//        BOOL isNoMoreData = NO;
//        [self.searchArray removeAllObjects];
//        [self tableViewDisplayWitMessage:@"没有数据" rowCount:[rsp.recordList count]];
//        if ([rsp.recordList count]>0) {
//            [self addRefreshFooter];
//            [self.tableView.mj_footer resetNoMoreData];
//            [self.searchArray addObjectsFromArray:rsp.recordList];
//            if(self.searchArray.count>=rsp.totalCount){//没数据了
//                isNoMoreData = YES;
//            }
//        }
//        [self.tableView reloadData];
//        [self.tableView.mj_header endRefreshing];
//        if(isNoMoreData){
//            [self.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
//    }];
}



- (void)loadMoreProductWithSearch{
    self.currentSearchPageNumber++;
//    ProductListAPI *api = [[ProductListAPI alloc]initWithPageSize:self.tableDataExtend.pageSize index:self.currentSearchPageNumber sortType:self.sortType sortRule:self.sortRule status:self.getStatus];
//    api.keyword = self.searchKey;
//    [api startCedarRequestWithCompletionBlock:^(CedarBaseResponse * _Nullable response) {
//        if (response.code!= ResponseTypeScuess) {
//            [self.tableView.mj_footer endRefreshing];
//            return;
//        }
//        ProductListRsp *rsp = [ProductListRsp mj_objectWithKeyValues:response.dataObject];
//        BOOL isNoMoreData = NO;
//        if ([rsp.recordList count]>0) {
//            [self.searchArray addObjectsFromArray:rsp.recordList];
//            [self.tableView reloadData];
//            [self.tableView.mj_footer endRefreshing];
//            if(self.searchArray.count>=rsp.totalCount){//没数据了
//                isNoMoreData = YES;
//            }
//        }
//        if(isNoMoreData){
//            [self.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
//    }];
}


#pragma mark refresh

- (void)resetRefreshData {
    if (self.isSearchMode) {
        [self refreshProductWithSearch];
    }else{
        [self publish:ProductChild_Notification];
        [self refreshProduct];
    }
}

- (void)loadMoreData {
    if (self.isSearchMode) {
        [self loadMoreProductWithSearch];
    }else{
        [self loadMoreProduct];
    }
}

- (void)beginRefresh{
    [self.tableView.mj_header beginRefreshing];
}

- (void)addRefreshFooter{
    if(!self.tableView.mj_footer){
        [UIConfigure  configLoadMoreInTableView:self.tableView target:self action:@selector(loadMoreData)];
    }
}

-  (void)removeRefreshFooter{
    if (self.tableView.mj_footer) {
        [self.tableView.mj_footer removeFromSuperview];
    }
    //self.tableView.mj_footer  = nil;
}

- (void)tableViewDisplayWitMessage:(NSString *) message rowCount:(NSUInteger) rowCount{
    if (rowCount == 0) {
        UILabel *messageLabel = [UILabel new];
        messageLabel.text = message;
        messageLabel.font = PingFangZhongChangGuiForFont(13);
        messageLabel.textColor = [UIColor lightGrayColor];
        messageLabel.textAlignment = NSTextAlignmentCenter;
        [messageLabel sizeToFit];
        self.tableView.backgroundView = messageLabel;
    } else {
        self.tableView.backgroundView = nil;
    }
}

#pragma mark - Table view data source


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;//section头部高度
}

//section头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    view.backgroundColor = kSeparateLineColor;
    return view;
}

/*
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
 ProductListItemRsp *productItem = nil;
 if (indexPath.section <  [self.tableDataExtend.listData count]) {
 productItem =  self.tableDataExtend.listData[indexPath.section];
 }
 return   [ProductCell heightForCell:productItem];
 }*/

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    if (self.isSearchMode) {
//        return [self.searchArray count];
//    }else{
//        return [self.tableDataExtend.listData count];
//    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderListCellIdentifier"];
//    ProductListItemRsp *productItem = nil;
//    if(self.isSearchMode){
//        if (indexPath.section <  [self.searchArray count]) {
//            productItem =  self.searchArray[indexPath.section];
//        }
//    }else{
//        if (indexPath.section <  [self.tableDataExtend.listData count]) {
//            productItem =  self.tableDataExtend.listData[indexPath.section];
//        }
//    }
//    [cell updateCellData:productItem];
//    @weakify(self)
//    cell.selectCellBlock = ^(id data) {
//        @strongify(self)
//        ChildProductVC *vc = [[ChildProductVC alloc]init];
//        ProductListItemRsp *productItem =  data;
//        vc.productId =  productItem.productId;
//        [self.navigationController pushToNewViewController:vc];
//    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    ChildProductVC *vc = [[ChildProductVC alloc]init];
//    ProductListItemRsp *productItem =  nil;
//    if(self.isSearchMode){
//        if (indexPath.section <  [self.searchArray count]) {
//            productItem =  self.searchArray[indexPath.section];
//        }
//    }else{
//        if (indexPath.section <  [self.tableDataExtend.listData count]) {
//            productItem =  self.tableDataExtend.listData[indexPath.section];
//        }
//    }
//    vc.productId =  productItem.productId;
//    vc.productTitle = productItem.productName;
//    [self.navigationController pushToNewViewController:vc];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [UIConfigure tableViewFromFactory];
        _tableView.rowHeight = 200;//固定行高
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[OrderListCell class] forCellReuseIdentifier:@"OrderListCellIdentifier"];
        
//        UIView * searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 41)];
//        searchView.backgroundColor = [UIColor clearColor];
//        searchView.clipsToBounds = YES;
//        [searchView addSubview:self.searchBar];
//        
//        _tableView.tableHeaderView = searchView;
//        
        CGFloat height = 20;
        if (IsPhoneX) {
            height = 60;
        }
        
        UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
        bottomView.backgroundColor = kSeparateLineColor;
        _tableView.tableFooterView = bottomView;
    }
    return _tableView;
}

#pragma mark - SearchBar

#pragma mark   UISearchBarDelegate

//- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
//    return YES;
//}

- (void)requestSearchKeyWorld:(NSNumber *)count{
    if (self.searchInputCount == [count integerValue]) {
        //[self.searchAPI stop];
        if (self.searchArray) {
            [self.searchArray removeAllObjects];
        }
        self.currentSearchPageNumber = 1;
        [self.tableView.mj_footer resetNoMoreData];
        [self refreshProductWithSearch];
    }
}



- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if([searchText length] == 0){
        if (self.searchArray) {
            [self.searchArray removeAllObjects];
        }
        [self.tableView reloadData];
        return;
    }
    self.searchKey = searchBar.text;
    self.searchInputCount ++;
    [self performSelector:@selector(requestSearchKeyWorld:) withObject:@(self.searchInputCount) afterDelay:0.5f];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = NO;
    searchBar.text = nil;
    [searchBar resignFirstResponder];
    self.searchBar.text = nil;
    self.tableView.backgroundView = nil;
    if(self.isSearchMode){
        self.isSearchMode = NO;
        self.searchKey = 0;
        if (self.searchArray) {
            [self.searchArray removeAllObjects];
        }
        //[self addRefreshFooter];
        [self.tableView.mj_footer resetNoMoreData];
        [self.tableView reloadData];
    }
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    self.isSearchMode = YES;
    searchBar.showsCancelButton = YES;       //显示“取消”按钮
    [self setSearchBarText:searchBar];
    if (IsEmptyStr(searchBar.text)) {
        if (self.searchArray) {
            [self.searchArray removeAllObjects];
        }
        [self.tableView reloadData];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.isSearchMode) {
        if(fabs( scrollView.contentOffset.y)>20){
            [self.searchBar resignFirstResponder];
        }
    }
}

- (void)setSearchBarText:(UISearchBar *)search{
    for (id obj in [self.searchBar subviews]) {
        if ([obj isKindOfClass:[UIView class]]) {
            for (id obj2 in [obj subviews]) {
                if ([obj2 isKindOfClass:[UIButton class]]) {
                    UIButton *btn = (UIButton *)obj2;
                    [btn setTitle:@"取消" forState:UIControlStateNormal];
                    [btn setTitleColor:kBlackColor forState:UIControlStateNormal];
                }
            }
        }
    }
}

- (NSMutableArray *)searchArray{
    if (!_searchArray) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}

- (UISearchBar *)searchBar{
    if(!_searchBar){
        _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(5, 10,SCREEN_WIDTH-10, 31)];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"搜索我的订单";
        [_searchBar setContentMode:UIViewContentModeCenter];
        UITextField  *seachTextFild = [_searchBar valueForKey:@"searchField"];
        if(seachTextFild){
            seachTextFild.backgroundColor = [UIColor colorWithRGB:0xe3e3e3];
            //修改字体大小
            seachTextFild.font = PingFangZhongChangGuiForFont(14);
            seachTextFild.layer.cornerRadius = 16.0f;
            seachTextFild.layer.borderColor = [UIColor colorWithRGB:0xe3e3e3].CGColor;
            seachTextFild.layer.borderWidth = 1;
            seachTextFild.layer.masksToBounds = YES;
        }
        _searchBar.backgroundImage = [UIImage imageWithColor:kAppBackgoundColor];
    }
    return _searchBar;
}

@end
